<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>

<h1>
	<fmt:message key="rewards.create.title" />
</h1>

<div id="message" class="alert alert-info">
	The reward has been created.
</div>

<div id="error" class="alert alert-danger">
	This should be hidden, so your JavaScript has a syntax error.
</div>

<spring:url value="/rewards" var="rewardUrl" />

<form:form modelAttribute="dining" action="${rewardUrl}" method="post" role="form" class="form-horizontal">
	<fieldset>
		<legend>
			<fmt:message key="rewards.create.legend"/>
		</legend>
		<div class="form-group">
			<label class="control-label col-sm-2" for="creditCardNumber">
				<fmt:message key="label.Reward.credit.card.number" />
			</label>
			<div class="col-sm-4">
				<form:input path="creditCardNumber" class="form-control" />
			</div>
			<div class="col-sm-6">
			</div>
		</div>
		<div class="form-group">
			<label class="control-label col-sm-2" for="amount">
				<fmt:message key="label.Reward.amount" />
			</label>
			<div class="col-sm-4">
				<form:input path="amount" class="form-control"/>
			</div>
			<div class="col-sm-6">
				<form:errors cssClass="alert alert-danger" path="amount" />
			</div>
		</div>
		<div class="form-group">
			<div class="col-sm-offset-2 col-sm-10">
				<button id="saveButton" type="submit" class="btn button-default">
					<fmt:message key="command.save" />
				</button>
			</div>
		</div>
	</fieldset>
</form:form>

<script type="text/javascript">
	var stompClient = null;

	/**
	 * On page load hide message and error divs, enhance saveButton to invoke
	 * processAjaxSubmit() when clicked
	 */
	$(function() {
		$("#message").hide();
		$("#error").hide();
		$("#saveButton").on('click', processAjaxSubmit);
		connect();
	});

	/**
	 * When save button is clicked: validate form then submit via an AJAX POST.
	 * If the the POST is successful (TO DO #4) send a message to /app/rewards
	 */
	function processAjaxSubmit(event) {
		var creditCardNumber = $("#creditCardNumber").val();
		var amount = $("#amount").val();

		if (creditCardNumber.length == 0) {
			$("#creditCardNumber").focus();   // Force focus to missing field
		} else if(amount.length == 0) {
			$("#amount").focus();   // Force focus to missing field
		} else {
			var rewardURL = "${rewardUrl}";

			// Setup request object
			var params = {
				creditCardNumber : creditCardNumber,
				amount : amount
			}

			// Submit new reward via na AJAX POST 
			$.post(rewardURL, params, function(data,textStatus,jqXhr) {
				// TODO 04: Send the credit card number to the /app/rewards destination
				//          As this is not a JavaScript course, all you need to do is
				//          uncomment the next line
				//stompClient.send('/app/rewards',{},creditCardNumber);

			<%--
				1. When we receive the response from the server, this callback is executed.
				   We are using it to send a web socket message to "/app/rewards".
				
				2. Now it's time to implement the method that handles that message on
				   the server side.  Move on to the next TO DO.
			--%>
			
				$("#error").hide();
				$("#message").fadeIn('fast');
			}).fail(function(data) {
				console.log("failed")
				$("#message").hide();
				$("#error").html("An error occurred on the server. Please specify a valid credit card number" +
					" (such as 1234123412341234) and a non-zero amount.");
				$("#error").fadeIn('fast');
			});
		}
		return false;
	}

	/**
	 * Log successful connection of STOMP client and subscribe to /topic/rewards
	 * Defines a callback to log any message received from /topic/rewards
	 *
	 * TODO 03: NOTE: Use this function as the callback for the STOMP
	 *                client connect() below.
	 */
	function subscribeUsingLoggingCallback(frame) {
		console.log('Connected: ' + frame);

		stompClient.subscribe('/topic/rewards', function(msg) {
			console.log('message received: ' + msg.body);
		});
	}

	/**
	 * Setup STOMP client.  HINT: See STOMP client slide in handout.
	 */
	function connect() {
		// TODO 03: Connect to the web socket endpoint with SockJS
		//          Use the ${rewardUrl} variable, e.g. var socket = new SockJS('${rewardUrl}');
		//          Use the stompClient variable declared at the top
		//          Setup STOMP over the web-socket and connect() 
		//          Register the subscribeJUsingLoggingCallback() callback function when invoking connect()
		//          HINT: See STOMP Client example in handout.

		// Using the instructions above, write three lines of JavaScript here ...
		
		<%-- TO DO 03 (continued) ...
		    1. Once this is done, deploy the application, and follow the "New Reward" link.
		       If there is a syntax error in your JavaScript, check the JavaScript console.
		       NOTE: The Web browser in STS doesn't expose the JavaScript console, use an EXTERNAL browser.
	
		    2. Submit a reward (use credit card number 1234123412341234 and an amount of 50.)
		       Check there's no error thanks to the JavaScript console of the browser 
		       If there's no error, it means you successfully connected to server!
	
		    3. Using "List Accounts", navigate to the account details page for account 123456789
		         (Keith and Keri Donald)
		       You should see the reward of the dining you've just submitted ($4 to each beneficiary).
		       Open the RewardController and check the newReward() method to see how the dining
		         submission is handled - NO NEED to modify this method.
	
		    4. Time to send some messages!
		       We want to send a web-socket message once the server has responded
		       successfully to the REST request. Move on to TO DO #4: scroll up to
		       function processAjaxSubmit() above.
		--%>
	}
</script>